package com.icloud.cer.rest.i18n;

import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.icloud.cer.rest.common.ContextHolder;
import com.icloud.cer.rest.msg.AbsMsgObject;
import com.icloud.cer.rest.util.StringUtils;

public class I18nUtil {
	private static final Logger log = LoggerFactory.getLogger(AbsMsgObject.class);
	private static Map<String, ResourceBundle> langPropertiesCache = new HashMap<String, ResourceBundle>();

	public static String getI18nLang(String fileBaseName, String key, Object... params) {
		// 取得用户的语言信息
		try {
			Locale userLocale=ContextHolder.getSessionLocale();
			String result = getI18nLang(userLocale, fileBaseName, key);
			if (null != result) {
				if(params != null && params.length > 0){
					MessageFormat mf = new MessageFormat(result, userLocale);
					result = mf.format(params);	
				}
			}
			return result;
		} catch (Exception e) {
			return null;
		}
	}

	public static ResourceBundle getResourceBundle(Locale locale, String fileBaseName) {
		if (null == fileBaseName || "".equals(fileBaseName.trim())) {
			throw new IllegalArgumentException("The properties file path(package.filename) can not be null.");
		}
		//add by mjj,20120313
		if(locale==null) {
			//取缺省locale
			locale = ContextHolder.getSessionLocale();
		}
		ResourceBundle rb = null;
		String cacheKey = fileBaseName + "_" + locale.toString();

		if (langPropertiesCache.containsKey(cacheKey)) {
			rb = langPropertiesCache.get(cacheKey);
		} else {
			//多线程并发时可能会加载多次，但如果对此同步会导致该锁跟日志输出的锁会互相等待资源导致死锁
			//加载失败时需要输出错误日志到appender会等待日志锁，同时在其他线程调用日志输出继承BaseException异常类的堆栈时，会调用toString方法来获取异常信息
			//在该方法中又会触发执行资源文件的加载此时需要等待该锁，最终导致死锁
			rb = ResourceBundle.getBundle(fileBaseName, locale);
			//加载失败了会存放null，避免下次加载
			langPropertiesCache.put(cacheKey, rb);
		}
		
		if(rb==null){
			log.warn("resource bundle not found:"+ fileBaseName);
		}
		return rb;
	}


	public static String getI18nLang(Locale locale, String fileBaseName, String key) {
		if(key==null) {
			return null;
		}
		ResourceBundle rb = getResourceBundle(locale, fileBaseName);
		return (rb == null) ? null : rb.getString(key);
	}
	
	
	public static String toString(Locale locale){
		if(locale.getCountry().length()==0){
			return locale.getLanguage(); 
		}else{
			return new StringBuilder(locale.getLanguage()).append('_').append(locale.getCountry()).toString();	
		}
	}
	
	public static Locale fromString(String locale){
		if(StringUtils.isEmpty(locale)) {
			return null;
		}
		int n=locale.indexOf('_');
		if(n<0){
			return new Locale(locale);
		}else{
			return new Locale(locale.substring(0,n),locale.substring(n+1));
		}
	}

}
